<?php declare(strict_types=1);
/**
 * Created by IntelliJ IDEA
 * Author: 张伯发
 * Date  : 2019/11/21
 * Time  : 11:32
 */

namespace App\Service;


use App\Dto\Request\Members\MembersVerifyCodeRequestDTO;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Bean\Annotation\Mapping\Inject;
use Swoft\Redis\Pool;
use Xiaoproject\Common\Base\BaseService;

/**
 * Class VerifyCodeService
 * @author 张伯发 2019/11/21 11:32
 * @Bean()
 */
class VerifyCodeService extends BaseService
{
    /**
     * @var string
     */
    private const MEMBERS_REGISTER_CODE = 'members_register_code:';

    private const MEMBERS_REGISTER_TIMEOUT = 10 * 60;

    /**
     * @Inject()
     * @var Pool
     */
    private $redis;


    /**
     *
     * @param string $phone
     * @return string|null
     * @author 张伯发 2019/11/21 11:35
     */
    public function getMembersRegisterCode(string $phone) : ?string
    {
        if (empty($phone)) return null;

        $result =  $this->redis->get($this->createMembersRegisterCodeCacheKey($phone));
        if ($result === false) return null;
        return strval($result);
    }

    /**
     *
     * @param MembersVerifyCodeRequestDTO $membersVerifyCodeDTO
     * @param int $verifyCodeLength
     * @return bool
     * @author 张伯发 2019/11/21 11:43
     */
    public function setMembersRegisterCode(MembersVerifyCodeRequestDTO $membersVerifyCodeDTO, int $verifyCodeLength = 6): bool
    {
        $phone      = $membersVerifyCodeDTO->getPhone();
        $verifyCode = strval(getRandom($verifyCodeLength));
        if (empty($phone) || empty($verifyCode)) return false;

        return $this->redis->set($this->createMembersRegisterCodeCacheKey($phone), $verifyCode, self::MEMBERS_REGISTER_TIMEOUT);
    }

    /**
     * @param $phone
     * @return int
     * @author 张伯发 2019/11/21 15:31
     */
    public function delMembersRegisterCode($phone) : int
    {
        $cacheKey = $this->createMembersRegisterCodeCacheKey($phone);
        $exists = $this->redis->exists($cacheKey);
        if ($exists) {
            return $this->redis->del($cacheKey);
        }
        return 0;
    }

    /**
     * 创建会员注册码的cache key
     * @param $phone
     * @return string
     * @author 张伯发 2019/11/21 15:30
     */
    private function createMembersRegisterCodeCacheKey($phone) : string
    {
        return self::MEMBERS_REGISTER_CODE . $phone;
    }
}
